import { ValidationPipe } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { NestFactory } from '@nestjs/core'
import * as session from 'express-session'
import * as passport from 'passport'
import { AppModule } from './app.module'
import { connectDB } from './config/database'

async function bootstrap() {
  // 初始化数据库连接
  await connectDB()

  const app = await NestFactory.create(AppModule)
  const configService = app.get(ConfigService)

  // 配置全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
    })
  )

  // 配置session
  app.use(
    session({
      secret: configService.get<string>('SESSION_SECRET'),
      resave: false,
      saveUninitialized: false,
      cookie: {
        maxAge: 24 * 60 * 60 * 1000, // 1天
        httpOnly: true,
      },
    })
  )

  // 初始化passport
  app.use(passport.initialize())
  app.use(passport.session())

  // 启用CORS
  app.enableCors({
    origin: configService.get<string>('CLIENT_URL'),
    credentials: true,
  })

  // 启动应用
  const port = configService.get<number>('PORT')
  await app.listen(port)
  console.log(`Application is running on: http://localhost:${port}`)
}
bootstrap()
